package org.hbnu.webregisterlogin.controller;

import org.hbnu.webregisterlogin.entity.Users;
import org.hbnu.webregisterlogin.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

//用户请求控制器
@Controller
public class UsersController {

    //需要用户服务对象
    @Autowired
    UsersService usersService;


    //注册功能，请求地址是 /registration
    // 如果注册成功返回 ok,如果注册失败返回 fail或失败理由
    // 用户注册需要：账号，密码，重复密码，昵称，年龄，性别，电话，地址
    @RequestMapping("/registration")
    @ResponseBody
    public String registration(@RequestBody Map<String, String> map) {

        //获取参数
        String email = map.get("email");
        String password = map.get("password");
        String password2 = map.get("password2");
        String nickname = map.get("nickname");
        String age = map.get("age");
        String sex = map.get("sex");
        String phone = map.get("phone");
        String address = map.get("address");

        //输出调试
        System.out.println("eamil=" + email);
        System.out.println("password=" + password);

        //注册条件检查
        if (password.length() < 6) {
            return "密码长度必须大于6";
        }
        if (!password.equals(password2)) {
            return "您输入的2次密码不一致";
        }
        if (password.trim().equals(" ") || password.equals("")) {
            return "您输入的密码不能包括空格或全为空格";
        }

        if (usersService.findByEmail(email) != null) {
            return "您输入的邮箱已注册！";
        }

        //添加到数据
        Users users = new Users();
        users.setEmail(email);
        users.setPassword(password);
        users.setNickname(nickname);
        users.setAge(Integer.parseInt(age));
        users.setSex(Integer.parseInt(sex));
        users.setPhone(phone);
        users.setAddress(address);

        System.out.println("开始注册");


        //注册成功
        usersService.add(users);

        System.out.println("注册成功！");


        return "ok";


    }


    //用户登录（用户查询）,服务地址是：/login
    //用户登录需要接受：邮箱(email) 和 密码(password)
    //如果登录成功 返回：ok ，登录失败返回:fail
    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestBody Map<String, String> map) {

        //获取参数
        String email = map.get("email");
        String password = map.get("password");

        //调试
        System.out.println("email:" + email);
        System.out.println("password:" + password);

        //用邮箱查询用户
        if (usersService.findByEmail(email)==null){
            return "用户不存在";
        }

        //判断密码正确
        if (!usersService.findByEmail(email).getPassword().equals(password)){
            return "密码错误！";
        }

        return "ok";
    }
}